#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>

#include "Common.hpp"

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string gsep = ": ";

using namespace LogModule;

class Dictionary
{
private:
	bool LoadDictionary()
	{
		std::string file = _path + _filename;
		// 以读模式打开文件，file.c_str() 将 std::string 转为 const char*，适配 ifstream 构造函数
		std::ifstream in(file.c_str());
		if (!in.is_open())
		{
			LOG(LogLevel::ERROR) << "open file" << file << "error";
			return false;
		}

		std::string line;
		while (std::getline(in, line))
		{
			std::string key;
			std::string value;
			if (SplitString(line, &key, &value, gsep))
			{
				_dictionary.insert(std::make_pair(key, value));
			}
		}

		in.close();
		return true;
	}

	// 划分字符串
	bool SplitString(std::string line, std::string *key, std::string *value, const std::string &sep)
	{
		auto pos = line.find(sep);
		if (pos == std::string::npos) //npos是一个静态成员常量，用于表示string中找不到子字符串或字符
			return false;
		*key = line.substr(0, pos);
		*value = line.substr(pos + sep.size());
		if (key->empty() || value->empty())
			return false;

		return true;
	}

public:
	Dictionary(const std::string &path = gpath, const std::string &filename = gdictname)
		: _path(path), _filename(filename)
	{
		LoadDictionary();
	}

	std::string Translate(const std::string &word)
	{
		auto iter = _dictionary.find(word);
		if (iter == _dictionary.end())
			return "None";

		return iter->second;
	}
	void Print()
	{
		for(auto& item : _dictionary) // 语法糖，item直接对应 “迭代器解引用后的元素”(*it)
		{
			std::cout << item.first << ": " << item.second << std::endl;
		}
	}
	~Dictionary()
	{
	}

private:
	std::unordered_map<std::string, std::string> _dictionary;
	std::string _path;
	std::string _filename;
};
